package com.whfc.base.queue;

import com.whfc.base.dao.AppMessageMapper;
import com.whfc.base.entity.AppMessage;
import com.whfc.base.manager.SmsMgr;
import com.whfc.common.constant.QueueConst;
import com.whfc.common.enums.AppMessageType;
import com.whfc.common.enums.AppWarnModuleType;
import com.whfc.common.enums.AppWarnMsgChannel;
import com.whfc.common.result.ResultEnum;
import com.whfc.common.third.sms.SmsApi;
import com.whfc.common.util.JSONUtil;
import com.whfc.entity.dto.msg.AppMsgToUserDTO;
import com.whfc.entity.dto.msg.PushMsgDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author sun_guodong
 * @description
 * @date 2020-05-22
 */
@Component
@RabbitListener(queues = QueueConst.PUSH_SMS)
public class SmsDataQueueMessageListener {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private AppMessageMapper appMessageMapper;

    @Autowired
    private SmsMgr smsMgr;

    @RabbitHandler
    public void process(String textMsg) {
        logger.info("短信消息==================》 {}",textMsg);
        PushMsgDTO pushMsgDTO = JSONUtil.parseObject(textMsg, PushMsgDTO.class);
        if (pushMsgDTO != null) {
            List<Integer> msgChannelList = pushMsgDTO.getMsgChannelList();
            List<AppMsgToUserDTO> toUserList = pushMsgDTO.getToUserList();
            if (msgChannelList != null && msgChannelList.contains(AppWarnMsgChannel.SMS.value())) {
//                logger.info("push_sms_listener:{}", textMsg);
                //消息分发
                AppMessage srcMessage = new AppMessage();
                srcMessage.setDeptId(pushMsgDTO.getDeptId());
                srcMessage.setTime(pushMsgDTO.getTime());
                srcMessage.setTitle(pushMsgDTO.getTitle());
                srcMessage.setContent(pushMsgDTO.getContent());
                srcMessage.setModuleType(pushMsgDTO.getModuleType());
                srcMessage.setMsgObjectId(pushMsgDTO.getMsgObjectId());
                srcMessage.setMsgType(AppMessageType.SERVICE.value());
                srcMessage.setMsgChannel(AppWarnMsgChannel.SMS.value());

                List<AppMessage> messageList = new ArrayList<>(toUserList.size());
                for (AppMsgToUserDTO toUserDTO : toUserList) {
                    AppMessage message = this.copy(srcMessage);
                    message.setToUserId(toUserDTO.getUserId());
                    message.setToUserName(toUserDTO.getNickName());
                    message.setToUserPhone(toUserDTO.getPhone());
                    messageList.add(message);
                }

                //消息存储
                if (messageList.size() > 0) {
                    logger.info("生成报警消息:sms:::::{}", JSONUtil.toString(messageList));
                    this.addMessage(messageList);
                }

                //消息推送
                for (AppMessage msg : messageList) {
                    this.sendMsg(msg);
                }
            }
        }
    }

    /**
     * 批量新增消息
     *
     * @param messageList
     */
    private void addMessage(List<AppMessage> messageList) {
        appMessageMapper.batchInsert(messageList);
    }

    /**
     * 更新短信状态(state=3)
     *
     * @param id
     */
    private void updateSmsState(Integer id) {
        appMessageMapper.updateSmsState(id);
    }

    /**
     * 短信消息
     *
     * @param msg
     */
    private void sendMsg(AppMessage msg) {

        Integer id = msg.getId();
        try {
            String result = "";
            String content = msg.getContent();
            String deviceName = content.substring(0, content.indexOf("在"));
            String rule = content.replaceAll("监测到", "").replaceAll("出现", "").split(",")[1];
            String userName = msg.getToUserName();
            String phone = msg.getToUserPhone();
            Integer moduleType = msg.getModuleType();
            String title = msg.getTitle();
            Date time = msg.getTime();
            SmsApi smsApi = smsMgr.SmsApi(phone);
            if (AppWarnModuleType.MACH.value().equals(moduleType) || AppWarnModuleType.EQUIP.value().equals(moduleType)) {
                result = smsApi.sendSmsMach(phone, userName, time, deviceName, rule);
            }
            if (AppWarnModuleType.FIM.value().equals(moduleType)) {
                result = smsApi.sendSmsFim(phone, userName, time, deviceName, rule);
            }
            if (AppWarnModuleType.ENV.value().equals(moduleType)) {
                result = smsApi.sendSmsEnv(phone, userName, time, deviceName, rule);
            }
            if (AppWarnModuleType.FSE.value().equals(moduleType)) {
                result = smsApi.sendSmsFse(phone, userName, time, deviceName, rule);
            }
            if (AppWarnModuleType.EMP.value().equals(moduleType)) {
                result = smsApi.sendSmsEmp(phone, userName, time, deviceName, rule);
            }
            if (AppWarnModuleType.ROTARY.value().equals(moduleType)) {
                result = smsApi.sendSmsRotary(phone, userName, time, deviceName, rule);
            }

            if (!ResultEnum.SUCCESS.getCode().equals(result)) {
                throw new Exception("调用短信接口失败");
            }
        } catch (Exception ex) {
            this.updateSmsState(id);
            logger.error("push_sms_listener", ex);
        }
    }

    /**
     * 拷贝消息对象
     *
     * @param message
     * @return
     */
    private AppMessage copy(AppMessage message) {
        AppMessage desMessage = new AppMessage();
        BeanUtils.copyProperties(message, desMessage);
        desMessage.setId(null);
        desMessage.setUpdateTime(null);
        desMessage.setCreateTime(null);
        return desMessage;
    }
}
